package xdu.lz.netty.e_zerocopy;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class ZeroCopyClient {

    public static void main(String[] args) throws Exception {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8899));
        //配置成阻塞，一直写完再返回。 不然一次性不一定写完 读到的全部内容
        socketChannel.configureBlocking(true);

        String fileName = "E:\\javaTools\\IDEA\\ideaIU-2018.1.1.exe";



        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        System.out.println("fileChannel = " + fileChannel.size());
        long startTime = System.currentTimeMillis();
        /**
         *
         * transferTo 是实现OS底层零拷贝的方法
         *<p> This method is potentially much more efficient than a simple loop
         ** that reads from this channel and writes to the target channel.  Many
         ** operating systems can transfer bytes directly from the filesystem cache
         ** to the target channel without actually copying them.  </p>
         * 注意：这个方法和OS有关，不同OS的transferTo一次能够读取的大小不一样
         *  win10下一次最多拷贝8M+
         */
        int position =  0 ;
        //long size = fileChannel.size();
        while (position < fileChannel.size()) {
            long count = fileChannel.transferTo(position, fileChannel.size(), socketChannel);
            if (count > 0) {
                position += count;
                //size -= count;
            }
        }

        System.out.println("发送总字节数：" + position + "，耗时： " + (System.currentTimeMillis() - startTime));
//        boolean flag = true ;
//        while ( flag==true){
//
//        }
        fileChannel.close();
        socketChannel.close();
    }
}
